package com.demo.common.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.demo.common.model.Blog;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
/**
 * JFinal Model 案例
 * @author xwalker
 */
public class ModelController extends Controller {
	/**
	 * 首页
	 */
	public void index(){
		setAttr("blogs", Blog.dao.find("select * from blog order by publishTime desc"));
		render("index.jsp");
	}
	public void search(){
		String keywords=getPara("keywords");
		keepPara();
		setAttr("blogs", Blog.dao.find("select * from blog where title like '%"+keywords+"%' order by publishTime desc"));
		render("index.jsp");
	}
	/**
	 * 分页查询
	 */
	public void paginate(){
		Integer pageNumber=getParaToInt("pageNumber");
		if(pageNumber==null||pageNumber<=0){
			pageNumber=1;
		}
		Page<Blog> page=Blog.dao.paginate(pageNumber, 6, "select *","from blog");
		setAttr("blogPage", page);
		render("page.jsp");
	}
	/**
	 * 进入编辑页面
	 */
	public void form(){
		Integer id=getParaToInt("id");
		if(id!=null&&id>0){
			setAttr("blog", Blog.dao.findById(getPara("id")));
		}
		render("form.jsp");
	}
	/**
	 * 测试model新增 必须使用new创建
	 */
	public void randomSave(){
		//限制添加次数
		if(checkBlogCount(10)){
			render("count.html");
			return;
		}
		Blog blog=new Blog();
		Date now=new Date();
		String nowStr=new SimpleDateFormat("yyyyMMddhhmmss").format(now);
		blog.set("title", "小木学堂"+nowStr);
		blog.set("content", "content"+nowStr);
		blog.set("publishTime",now);
		blog.save();
		redirect("/model");
	}
	
	
	/**
	 * 保存 更新
	 */
	public void saveorupdate(){
		//限制添加次数
		if(checkBlogCount(10)){
			render("count.html");
			return;
		}
		//上传图像
		UploadFile file=getFile("img");
		Blog blog=getModel(Blog.class, "blog");
		if(file==null){
			setAttr("error", "请先上传一张图片");
			keepModel(Blog.class,"blog");
			render("form.jsp");
			return;
		}
		//获得表单数据转Model
		//判断保存或者更新
		if(blog.get("id")==null){
			//使用set赋值
			blog.set("publishTime", new Date());
			blog.save();
		}else if(blog.getInt("id")>0){
			blog.update();
		}
		//跳转首页
		redirect("/model");
	}
	
	/**
	 * 检测添加数据的数量 超过十个不在允许添加
	 */
	private boolean checkBlogCount(int maxCount) {
		long count=0;
		List result=Db.query("select count(*) from blog");
		if(result.size()==1){
			count = ((Number)result.get(0)).longValue();	
		}else if(result.size()>1){
			count=result.size();
		}
		return (int)count>=maxCount;
		
	}
	/**
	 * 删除
	 */
	public void delete(){
		Blog.dao.deleteById(getPara("id"));
		redirect("/model");
	}
}
